const express = require('express');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const app = express();
const port = 3000;

// 启用CORS
app.use(cors());

// 配置文件上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'firmware')
    },
    filename: function (req, file, cb) {
        cb(null, 'firmware.bin')
    }
});

const upload = multer({ storage: storage });

// 确保firmware目录存在
if (!fs.existsSync('firmware')) {
    fs.mkdirSync('firmware');
}

// 读取版本信息
function readVersionInfo() {
    const versionPath = path.join(__dirname, 'firmware', 'version.json');
    if (fs.existsSync(versionPath)) {
        return JSON.parse(fs.readFileSync(versionPath, 'utf8'));
    }
    return {
        version: "",
        url: "http://本机内网IP:3000/firmware/firmware.bin"
    };
}

// 获取版本信息
app.get('/version.json', (req, res) => {
    res.json(readVersionInfo());
});

// 获取固件文件
app.get('/firmware/firmware.bin', (req, res) => {
    const filePath = path.join(__dirname, 'firmware', 'firmware.bin');
    if (fs.existsSync(filePath)) {
        res.download(filePath);
    } else {
        res.status(404).send('固件文件不存在');
    }
});

// 上传新固件
app.post('/upload', upload.single('firmware'), (req, res) => {
    if (!req.file) {
        return res.status(400).send('没有上传文件');
    }
    
    // 更新版本号
    const versionInfo = readVersionInfo();
    const versionParts = versionInfo.version.split('.');
    versionParts[2] = (parseInt(versionParts[2]) + 1).toString();
    versionInfo.version = versionParts.join('.');
    
    // 保存新的版本信息
    fs.writeFileSync(
        path.join(__dirname, 'firmware', 'version.json'),
        JSON.stringify(versionInfo, null, 4)
    );
    
    res.json({
        message: '固件上传成功',
        version: versionInfo.version
    });
});

// 启动服务器
app.listen(port, '0.0.0.0', () => {
    console.log(`OTA测试服务器运行在 http://0.0.0.0:${port}`);
    console.log(`当前固件版本: ${readVersionInfo().version}`);
}); 